package org.sninwo.lnbook.book.service;

import java.util.List;

import javax.annotation.Resource;

import org.sninwo.lnbook.base.Page;
import org.sninwo.lnbook.book.dao.BookDao;
import org.sninwo.lnbook.book.dao.BookTypeDao;
import org.sninwo.lnbook.book.dao.OriginalDao;
import org.sninwo.lnbook.book.entity.Book;
import org.sninwo.lnbook.book.entity.BookType;
import org.sninwo.lnbook.uitls.LnBookUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class BookManager {	
	@Resource private BookDao bookDao;
	@Resource private BookTypeDao bookTypeDao;
	@Resource private OriginalDao originalDao;
	
	/**
	 * 保存书籍内容，并更新对应的原文内容
	 */
	public void saveBook(Book book){
		bookDao.save(book);
		//组合出原文并保存
		String typeName = bookTypeDao.get(book.getTypeId()).getName();
		originalDao.saveFormBook(book, typeName);
	}

	/**
	 * 保存书籍，如果相同类别、书名和作者的记录已存在，则更新，否则新增。
	 * 主要在导入时使用。
	 */
	public void saveUniqueBook(Book newBook){
		Book oldBook = bookDao.findImportUnique(newBook.getTypeId(), newBook.getName(), newBook.getAuthor());
		if (oldBook != null){
			BeanUtils.copyProperties(newBook, oldBook, new String[]{"id", "originalId"});
			saveBook(oldBook);
		}
		else{
			saveBook(newBook);
		}
	}

	@Transactional(readOnly = true)
	public Book getBook(Long id){
		Book book = bookDao.get(id);
		return LnBookUtils.cloneBean(book);
	}

	/**
	 * 删除书籍及其原文
	 */
	public void removeBooks(long[] ids){
		for (long id : ids){
			Book book = bookDao.get(id);
			if (book.getOriginalId() != null){
				originalDao.delete(book.getOriginalId());
			}
			bookDao.delete(book);
		}
	}

	@Transactional(readOnly = true)
	public Page<Book> queryBook(Page<Book> page, Book book){
		return bookDao.findPage(page, book);
	}

	@Transactional(readOnly = true)
	public List<Book> findAllBooksByTypeId(Long typeId){
		return bookDao.findAllBooksByTypeId(typeId);
	}

	@Transactional(readOnly = true)
	public long getBookCount(Long typeId){
		return bookDao.getCount("typeId = ?", typeId);
	}
	
	@Transactional(readOnly = true)
	public BookType getBookType(Long id){
		return LnBookUtils.cloneBean(bookTypeDao.get(id));
	}
	
	public void saveBookType(BookType bookType){
		bookTypeDao.save(bookType);
	}
	
	public void removeBookType(Long typeId){
		bookTypeDao.delete(typeId);
	}

	@Transactional(readOnly = true)
	public List<BookType> getAllBookTypes(){
		return bookTypeDao.getAll("seq", true);
	}

	@Transactional(readOnly = true)
	public int getMaxSeqOfBookType(){
		return bookTypeDao.getMaxSeq();
	}
}
